<?php
declare (strict_types = 1);

namespace app\controller;

use app\validate\Avatar;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Request;

class ChatApi
{
    // 文本消息的数据持久化
    public function save_message(){
        if(Request::instance()->isAjax()){
            $message = input("post.");
            $datas["fromid"] = $message["fromid"];
            $datas["fromname"] = $this->getName($datas["fromid"]);
            $datas["toid"] = $message["toid"];
            $datas["toname"] = $this->getName($datas["toid"]);;
            $datas['content'] = $message['data'];
            $datas['time'] = $message['time'];
//            $datas['isread'] = $message['isread'];
            $datas['isread'] = 0;
            $datas['type'] = 1;

            Db::name('chat_communication')->insert($datas);
        }
    }
    // 根据用户id返回用户姓名
    public function getName($uid){

        $userifo = Db::name("users")->where('id', $uid)->value('name');

        return $userifo;
    }

    // 根据用户id获取聊天双方头像信息
    public function get_avatar(){
        if (Request::instance()->isAjax()){
            $fromid = input('fromid');
            $toid = input('toid');

            $frominfo = Db::name('users')->where('id', $fromid)->value('avatar');
            $toinfo = Db::name('users')->where('id', $toid)->value('avatar');

            return [
                'from_avatar' => $frominfo ,
                'to_avatar' => $toinfo
            ];
        }
    }

    // 获取名称
    public function get_name(){
        if (Request::instance()->isAjax()){
            $fromid = input('fromid');
            $toid = input('toid');

            $frominfo = Db::name('users')->where('id', $fromid)->value('name');
            $toinfo = Db::name('users')->where('id', $toid)->value('name');

            return [
                'from_name' => $frominfo ,
                'to_name' => $toinfo
            ];
        }
    }

    // 加载聊天记录
    public function load(){

        if (Request::instance()->isAjax()){

            $fromid = input('fromid');
            $toid = input('toid');
            $last_page = Db::name('chat_communication')->where(['fromid'=>$fromid, 'toid'=>$toid])->whereOr(['fromid'=>$toid, 'toid'=>$fromid])->order('id')->paginate(10)->lastPage();
            $messages = Db::name('chat_communication')->where(['fromid'=>$fromid, 'toid'=>$toid])->whereOr(['fromid'=>$toid, 'toid'=>$fromid])->order('id')->paginate([
                'list_rows' => 10,
                'page' => $last_page
            ]);

            return $messages;
        }

    }

    // 上传图片
    public function uploading(Request $request){
        $file = $file = $request::file('file');;
        $fromid = input('fromid');
        $toid = input('toid');
        $online = input('online');
        // 验证图片
        try {
            validate(Avatar::class)->check(['avatar' => $file]);
        } catch (ValidateException $e) {
            $error = $e->getError();
            // 返回错误信息
            return json($error, 400);
        } catch (\Exception $e) {
            return json('请选择图片', 400);
        }

        $file_path = '/storage/'.Filesystem::disk('public')
                ->putFile('uploads', $file);

        // 替换反斜杠
        $file_path = str_replace('\\', '/', $file_path);

        $data = [
            'content'=>$file_path,
            'fromid'=>$fromid,
            'toid'=>$toid,
            'fromname'=>$this->getName($fromid),
            'toname'=>$this->getName($toid),
            'time'=>time(),
//            'isread'=>$online,
            'isread'=>0,
            'type'=>2
        ];

        $message_id = Db::name('chat_communication')->insertGetId($data);
        if ($message_id){
            return ['status'=>'ok','img_name'=>$file_path];
        } else {
            return ['status'=>'false'];
        }
    }

    // 根据uid获取头像
    public function get_avatar_one($uid){
        $fromavatar = Db::name('users')->where('id',$uid)->value('avatar');

        return $fromavatar;
    }

    // 获取用户有多少未读消息
    public function getCountNoread($fromid, $toid){
        return Db::name('chat_communication')->where(['fromid'=>$fromid, 'toid'=>$toid, 'isread'=>0])->count('id');
    }

    // 获取用户之间最后一条消息
    public function getLastMessage($fromid, $toid){
        $info = Db::name('chat_communication')->where(['fromid'=>$fromid,'toid'=>$toid])->whereOr(['fromid'=>$toid,'toid'=>$fromid])->order('id DESC')->limit(1)->find();

        return $info;
    }
    // 根据fromid来获取当前用户聊天列表
    public function get_list(){
        if(Request::instance()->isAjax()){
            $fromid = input('id');
            $info = Db::name('chat_communication')->field(['fromid', 'toid', 'fromname'])->where('toid', $fromid)->group('fromid')->select();

            $row = array_map(function ($res){
                return [
                    'avatar_url'=>$this->get_avatar_one($res['fromid']),
                    'username'=>$res['fromname'],
                    'countNoread'=>$this->getCountNoread($res['fromid'], $res['toid']),
                    'last_message'=>$this->getLastMessage($res['fromid'], $res['toid']),
                    'chat_page'=>'http://tpblog.com/chat?fromid='.$res['toid'].'&toid='.$res['fromid']
                ];
            }, $info->all());

            return $row;
        }
    }

    public function changeNoRead(){
        if (Request::instance()->isAjax()) {
            $fromid = input('toid');
            $toid = input('fromid');
            Db::name('chat_communication')->where(['fromid'=>$fromid, 'toid'=>$toid])->update(['isread' => 1]);
        }
    }
}
